package opl.dal;

import java.util.ArrayList;
import java.util.List;

import opl.tables.ITable;
import opl.tables.NotificationTable;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;

public class DbHelper extends SQLiteOpenHelper {

	private static final int DB_VERSION = 1;
	private static final String DB_NAME = "OPL_DB";
	private static List<ITable> _lstTables;

	private DbHelper(Context context, String name, CursorFactory factory,
			int version) {
		super(context, name, factory, version);

		if (_lstTables == null) {
			populateTables();
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		createTables(db);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		dropTables(db);
		onCreate(db);
	}

	private void createTables(SQLiteDatabase db) {
		for (int i = 0; i < _lstTables.size(); i++) {
			ITable table = _lstTables.get(i);
			table.createTable(db);
		}
	}

	private void dropTables(SQLiteDatabase db) {
		for (int i = 0; i < _lstTables.size(); i++) {
			ITable table = _lstTables.get(i);
			table.dropTable(db);
		}
	}

	private void populateTables() {
		_lstTables = new ArrayList<ITable>();
		_lstTables.add(new NotificationTable());
	}

	public static DbHelper createInstance(Context context) {
		return new DbHelper(context, DB_NAME, null, DB_VERSION);
	}

	private <T extends ITable> ITable getTableInstance(Class<T> tableType) {
		for (int i = 0; i < _lstTables.size(); i++) {
			ITable table = _lstTables.get(i);
			if (table.getClass() == tableType) {
				return table;
			}
		}
		return null;
	}

	public <T extends ITable> long insert(ContentValues cv, Class<T> tableType) {
		ITable table = getTableInstance(tableType);
		return table.insert(cv, getWritableDatabase());
	}

	public <T extends ITable> long update(ContentValues cv, String condition,
			Class<T> tableType) {
		ITable table = getTableInstance(tableType);
		return table.update(cv, condition, getWritableDatabase());
	}

	public <T extends ITable> long delete(String condition, Class<T> tableType) {
		ITable table = getTableInstance(tableType);
		return table.delete(condition, getWritableDatabase());
	}

	public <T extends ITable> Cursor select(String condition, Class<T> tableType) {
		ITable table = getTableInstance(tableType);
		return table.select(condition, getReadableDatabase());
		
	}
	public <T extends ITable> Cursor select(String condition,String orderBy,String limit, Class<T> tableType) {
		ITable table = getTableInstance(tableType);
		return table.select(condition,orderBy,limit, getReadableDatabase());
		
	}
	
}
